package com.kaikeba.servlet;

import com.jspsmart.upload.File;
import com.jspsmart.upload.SmartUpload;
import com.jspsmart.upload.SmartUploadException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.jsp.JspFactory;
import javax.servlet.jsp.PageContext;
import java.io.IOException;

@WebServlet(value = "/upload")
public class UploadServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1.创建对象
        SmartUpload smartUpload = new SmartUpload();
        //2.初始化
        //通过jsp工厂获取pageContext内置对象，再作为传数进行初始化
        PageContext pageContext = JspFactory.getDefaultFactory().getPageContext(this, req, resp, null, false, 1024 * 1024, true);
        //初始化需要pageContext对象（jsp内置对象）
        smartUpload.initialize(pageContext);
        //3.设置编码方式
        smartUpload.setCharset("utf-8");
        //4.上传
        try {
            smartUpload.upload();
        } catch (SmartUploadException e) {
            e.printStackTrace();
        }
        //5.保存文件
        //得到上传后文件虚拟路径
        File file = smartUpload.getFiles().getFile(0);
        //上传文件名称
        String fileName = file.getFileName();
        //指定服务器保存文件的路径
        String url = "uploadfile/"+fileName;

        //用虚拟路径进行 保存
        try {
            file.saveAs(url,File.SAVEAS_VIRTUAL);
        } catch (SmartUploadException e) {
            e.printStackTrace();
        }

        //是否保存成功?--->如果上传成功，则页面中显示该文件
        req.setAttribute("filename",fileName);

        String name = smartUpload.getRequest().getParameter("name");
        req.setAttribute("name",name);

        //跳转页面
        req.getRequestDispatcher("/main.jsp").forward(req,resp);

    }
}
